The example below shows us how to bind a ListBox using vb.NET. The ListBox comes from System.Windows.Controls namespace. It’s a list of items that can be selected.
First, create a new Visual Studio Project using VB.NET, then add a list box control to the main form as shown below:
For this example we will use the table below:
Design View
Data View
Now add the code that binds the ListBox myListBox:
VB.NET
Sub BindListBox() Dim connetionString = "Data Source=TutorialsPanel-DB\SQLEXPRESS; Initial Catalog=TutorialsPanel;Integrated Security=True;" Dim conn As System.Data.SqlClient.SqlConnection = New SqlClient.SqlConnection(connetionString) Dim da As New SqlDataAdapter Dim cmd As New SqlCommand Dim dt As New DataTable cmd.CommandText = "Select LanguageName from ProgrammingLanguage Order by LanguageName ASC" da.SelectCommand = cmd da.SelectCommand.Connection = conn da.Fill(dt) myListBox.DataSource = dt myListBox.DisplayMember = "LanguageName" myListBox.ValueMember = "LanguageName" End Sub
Then call this sub when the form loads:
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load BindListBox() End Sub
Now let’s popup a MessageBox when the ListBox is clicked:
Private Sub myListBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles myListBox.SelectedIndexChanged MessageBox.Show("You have selected: " + myListBox.Text) End Sub
Run the solution then select an item
Comments